<template>
    <div class="qr-box">
        <div style="width: 100%;">
            <v-textarea counter variant="solo" label="请输入文本内容" v-model="textQr"></v-textarea>
            <v-btn block @click="generateQrCode" :min-height="55">生成二维码</v-btn>
            <v-divider style="margin: 10px 0px;"></v-divider>
            <v-alert v-model="alertMsg" border="start" title="转换二维码" variant="tonal" closable
                color="deep-purple-accent-4">{{ errorMsg }}</v-alert>
        </div>
        <v-img class="qr-image" v-if="imageQr != null" :src="imageQr"></v-img>
    </div>
</template>
<script>
export default {
    data: () => ({
        alertMsg: false,
        textQr: "",
        imageQr: null,
        errorMsg: "",
    }
    ),
    methods: {
        generateQrCode() {
            if (this.textQr == null || this.textQr == "") {
                this.imageQr = null;
                this.errorMsg = "请先输入二维码的文本内容";
                this.alertMsg = true;
                return;
            }
            this.alertMsg = false;
            const QRCode = require('qrcode');
            const opts = {
                errorCorrectionLevel: 'L',
                type: 'image/png',
                quality: 100,
                margin: 1,
            };
            QRCode.toDataURL(this.textQr, opts)
                .then(url => {
                    this.imageQr = url;
                })
                .catch(err => {
                    this.imageQr = null;
                    this.errorMsg = "生成出错：" + String(err);
                    this.alertMsg = true;
                });
        }
    }
}
</script>
<style scoped>
.qr-box {
    display: flex;
    flex-direction: column;
    height: 100%;
}

.qr-image {
    flex: 1;
}
</style>
